import { useCallback, useRef } from 'react';
import { Toast } from 'antd-mobile';
import { ToastHandler } from 'antd-mobile/es/components/toast';

interface HideOptions {
  delayIsLoadingTime?: number; // 延迟改变isLoading的值 默认不延迟
}

export const useLoading = () => {
  const loadingRef = useRef<ToastHandler | null>(null);
  const loadingTimer = useRef<NodeJS.Timeout | null>(null);
  const isLoading = useRef(false);

  const hide = useCallback((options?: HideOptions) => {
    if (loadingRef.current && loadingTimer.current) {
      loadingRef.current.close();
      clearTimeout(loadingTimer.current);
    } else if (loadingTimer.current) {
      clearTimeout(loadingTimer.current);
    }

    loadingRef.current = null;
    loadingTimer.current = null;

    if (options?.delayIsLoadingTime) {
      setTimeout(() => {
        isLoading.current = false;
      }, options.delayIsLoadingTime);
    } else {
      isLoading.current = false;
    }
  }, []);

  const show = useCallback(() => {
    hide();
    isLoading.current = true;
    loadingTimer.current = setTimeout(() => {
      loadingRef.current = Toast.show({
        maskClassName: 'loading-mask',
        icon: 'loading',
        duration: 0,
        maskClickable: false,
      });
    }, 1000);
  }, [hide]);

  const getIsLoading = useCallback(() => {
    return isLoading.current;
  }, []);

  return {
    show,
    hide,
    getIsLoading,
  };
};